/*
 * File Name : mkdir.cpp
 * Auther : dream.liuguobiao
 * Create Date : 2010-5-19
 * Last Edit : 2010-5-19
 */

#include <iostream>

#include "mkdir.h"
#include "my_string.h"
#include "directory.h"

mkdir::mkdir( std::string *new_parameters)
:command(new_parameters)
{
}

int mkdir::run_command(){
  file_system *my_file_system = get_shell_environment()->get_file_system() ;
  user *current_login_user = get_shell_environment()->get_login_users()->top();
  std::string *mkdir_path = get_parameters();
  std::string current_path = *(my_file_system->get_current_directory()->get_path() );
  my_string *string_tool = my_string::get_my_string();
  std::string path_tmp = *mkdir_path;
  node *current_directory_tmp = my_file_system->get_current_directory();

  if( (*get_parameters())[0] != '/'){
    if( "/" != current_path )
      current_path += '/';
    current_path += (*mkdir_path) ;
  }
  std::queue<std::string > *all_path = string_tool->split_string( '/' , current_path);
  node *current_node = my_file_system->get_root();
  my_file_system->set_current_directory( current_node );
  while(  1 < all_path->size() ){
    current_node = my_file_system->find_node_just_current_directory( &all_path->front() );
    if( NULL == current_node ){
      my_file_system->set_current_directory( current_directory_tmp );
      std::cout<<"mkdir: cannot create directory `"<<path_tmp<<" : no this file or directory\n";
      return 0;
    }
    all_path->pop();
    //user *current_user = get_shell_environment()->get_login_users()->top();
    my_file_system->set_current_directory( current_node );
}
  if( 2 != ( current_node->get_mod() & 2) && my_file_system->get_current_directory()->get_userID() != current_login_user->get_ID() && 0 != current_login_user->get_ID() ){
    std::cout<<"mkdir: cannot create directory `"<<(*mkdir_path)<<"': Permission denied"<<std::endl;
    return 0;
  }
  node *new_node = new directory();
  new_node->set_userID( current_login_user->get_ID() );
  new_node->set_name( &all_path->front() );

  my_file_system->insert_node( new_node );
  my_file_system->set_current_directory( current_directory_tmp );
  return 0;
}
